from flask import Blueprint, request, jsonify, render_template, session, redirect, url_for
from app.extensions import db
from app.models.user import User

auth_bp = Blueprint('auth', __name__)


@auth_bp.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        data = request.json
        user = User.query.filter_by(username=data['username']).first()
        if user and user.check_password(data['password']):
            session['user_id'] = user.id
            session['username'] = user.username
            session['nickname'] = user.nickname
            session['avatar'] = user.avatar
            return jsonify({'status': 'success', 'message': '登录成功'})
        return jsonify({'status': 'error', 'message': '用户名或密码错误'}), 401
    # 已登录则跳首页
    userexit = User.query.filter_by(username=session.get('username')).first()
    if 'user_id' in session and userexit:
        return redirect(url_for('main.index'))
    return render_template('auth/login.html')


@auth_bp.route('/register', methods=['POST'])
def register():
    data = request.json
    # 验证必要字段是否存在
    required_fields = ['username', 'password', 'nickname']
    if not all(field in data for field in required_fields):
        return jsonify({'status': 'error', 'message': '请提供用户名、密码和昵称'}), 400

    # 检查用户名是否已存在
    if User.query.filter_by(username=data['username']).first():
        return jsonify({'status': 'error', 'message': '用户名已存在'}), 400

    # 创建新用户，包含昵称信息
    user = User(
        username=data['username'],
        nickname=data['nickname']
    )
    user.set_password(data['password'])

    db.session.add(user)
    try:
        db.session.commit()
        return jsonify({'status': 'success', 'message': '注册成功，请登录'})
    except Exception as e:
        db.session.rollback()
        return jsonify({'status': 'error', 'message': f'注册失败：{str(e)}'}), 500


@auth_bp.route('/logout')
def logout():
    session.pop('user_id', None)
    session.pop('username', None)
    session.pop('nickname', None)
    session.pop('avatar', None)
    return redirect(url_for('auth.login'))



